# coding=utf-8
from rest_framework import serializers
from django.db import models as django_models

from sutras import enums, models
from sutras.utils import tools


class AddWXNicknameListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        iterable = data.all() if isinstance(
            data, django_models.Manager) else data

        result_datas = []
        open_ids = []

        for item in iterable:
            result_data = self.child.to_representation(item)
            open_id = result_data["open_id"]
            result_datas.append(result_data)
            open_ids.append(open_id)

        wx_user_infos = tools.get_wx_user_infos(open_ids)
        for result_data in result_datas:
            open_id = result_data["open_id"]
            nickname = wx_user_infos[open_id].get("nickname")
            result_data["nickname"] = nickname
        return result_datas


class TypesetConfigList(serializers.ModelSerializer):

    class Meta:
        model = models.TypesetConfig


class MaterialConfigList(serializers.ModelSerializer):

    class Meta:
        model = models.MaterialConfig


class BindConfigList(serializers.ModelSerializer):

    class Meta:
        model = models.BindConfig


class FontColorConfigList(serializers.ModelSerializer):

    class Meta:
        model = models.FontColorConfig


class AdminUserList(serializers.ModelSerializer):

    class Meta:
        model = models.CustomUser
        fields = ("id", "uid", "nickname", "admin_role", "email", "join_time")


class ConsumerList(serializers.ModelSerializer):

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # TODO: 此处可优化
        user_level_info = models.UserLevelInfo.objects.get(user=instance)
        data["total_cost"] = user_level_info.total_cost
        data["transcript_num"] = user_level_info.finish_book_num
        data["print_num"] = user_level_info.print_book_num
        return data

    class Meta:
        list_serializer_class = AddWXNicknameListSerializer
        model = models.CustomUser
        fields = ("id", "uid", "open_id", "email", "phone", "join_time")


class ConsumerAddressList(serializers.ModelSerializer):

    class Meta:
        model = models.UserAddress
        fields = ("contact", "phone", "postcode", "address")


class ConsumerPrintOrderList(serializers.ModelSerializer):

    uid = serializers.CharField(source="user.uid")
    nickname = serializers.CharField(source="user.nickname")
    cost = serializers.CharField(source="total_should_pay")

    class Meta:
        model = models.PrintOrder
        fields = ("uid", "nickname", "serial_num", "cost",
                  "create_time", "pay_method", "pay_status")


class ConsumerFavoriteList(serializers.ModelSerializer):

    uid = serializers.CharField(source="user.id")
    open_id = serializers.CharField(source="user.open_id")
    sutra_edition_name = serializers.CharField(source="sutra_edition.name")

    def to_representation(self, instance):
        data = super().to_representation(instance)
        user = instance.user
        sutra_edition = instance.sutra_edition
        # 此处可优化
        data["favorite_num"] = models.UserFavorite.objects.filter(
            user=user).count()
        transcription = models.UserTranscription.objects.filter(
            user=user, sutra_edition=sutra_edition).order_by("-id").first()

        if transcription \
                and transcription.status == enums.UserTranscription.finished:
            transcript_status = 1  # 已抄完
        else:
            transcript_status = 0  # 未抄完
        data["transcript_status"] = transcript_status
        return data

    class Meta:
        list_serializer_class = AddWXNicknameListSerializer
        model = models.UserFavorite
        fields = ("uid", "open_id", "sutra_edition_name", "create_time")


class ConsumerTranscriptionList(serializers.ModelSerializer):

    uid = serializers.CharField(source="user.uid")
    open_id = serializers.CharField(source="user.open_id")
    sutra_edition_name = serializers.CharField(source="sutra_edition.name")

    def to_representation(self, instance):
        data = super().to_representation(instance)
        transcript_pages = models.UserPageTranscription.objects.filter(
            user_transcription=instance)
        # 此处可优化
        # 自抄页数
        data["self_num"] = transcript_pages.filter(
            assistant_user__isnull=True).count()
        # 助抄页数
        data["assistance_num"] = transcript_pages.filter(
            assistant_user__isnull=False).count()
        # 印刷状态 0:待印刷/1:已印刷
        if models.PrintOrder.objects.filter(
                user=instance.user, sutra_edition=instance.sutra_edition):
            data["print_status"] = 1
        else:
            data["print_status"] = 0
        return data

    class Meta:
        model = models.UserTranscription
        list_serializer_class = AddWXNicknameListSerializer
        fields = ("uid", "open_id", "sutra_edition_name", "finish_time")


class ConsumerAssistanceList(serializers.ModelSerializer):

    uid = serializers.CharField(source="assistant_user.uid")
    nickname = serializers.CharField(source="assistant_user.nickname")
    sutra_edition_name = serializers.CharField(
        source="user_transcription.sutra_edition.name")
    transcript_status = serializers.IntegerField(source="status")

    class Meta:
        model = models.UserPageTranscription
        fields = ("uid", "nickname", "sutra_edition_name", "finish_time",
                  "page_num", "trascript_status")


class PrintOrderList(serializers.ModelSerializer):

    def to_representation(self, instance):
        data = super().to_representation(instance)
        detail = models.PrintOrderDetail.objects.filter(
            print_order=instance, contact__isnull=False).first()
        if detail:
            data["contact"] = detail.contact
        else:
            data["contact"] = None
        return data

    class Meta:
        model = models.PrintOrder
        fields = ("id", "serial_num", "total_price",
                  "total_should_pay", "create_time", "pay_method",
                  "status", "pay_status")
